#!/usr/bin/env python
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dataset.

Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
https://huggingface.co/models?filter=text-generation
"""
# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments.
"""
导包
"""
import logging
import math
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional

import datasets
import evaluate
import torch
from datasets import load_dataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_FOR_CAUSAL_LM_MAPPING,
    AutoConfig,
    AutoModelForCausalLM,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    DefaultDataCollator,
    DataCollatorWithPadding,
    is_torch_xla_available,
    set_seed,
)
from transformers.testing_utils import CaptureLogger
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version
from transformers.utils import send_example_telemetry

from transformers.utils.versions import require_version

"""
检查版本 对datasets包的版本和自身版本进行约束
"""
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
# check_min_version("4.47.0.dev0")

require_version("datasets>=2.14.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
"""
注册日志名称
"""
logger = logging.getLogger(__name__)
"""
通过使用 _LazyAutoMapping 方法，将模型配置转换成配置对象的元祖列表
"""
MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys())
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
# print(MODEL_CONFIG_CLASSES)
"""
打印所有的配置列表
for i in list(set([str(conf) for conf in MODEL_CONFIG_CLASSES])):
    print(str(i))
<class 'transformers.models.stablelm.configuration_stablelm.StableLmConfig'>
<class 'transformers.models.mvp.configuration_mvp.MvpConfig'>
<class 'transformers.models.xlm_roberta.configuration_xlm_roberta.XLMRobertaConfig'>
<class 'transformers.models.ctrl.configuration_ctrl.CTRLConfig'>
<class 'transformers.models.camembert.configuration_camembert.CamembertConfig'>
<class 'transformers.models.gpt_neox.configuration_gpt_neox.GPTNeoXConfig'>
<class 'transformers.models.marian.configuration_marian.MarianConfig'>
<class 'transformers.models.data2vec.configuration_data2vec_text.Data2VecTextConfig'>
<class 'transformers.models.mamba2.configuration_mamba2.Mamba2Config'>
<class 'transformers.models.musicgen_melody.configuration_musicgen_melody.MusicgenMelodyConfig'>
<class 'transformers.models.big_bird.configuration_big_bird.BigBirdConfig'>
<class 'transformers.models.cohere.configuration_cohere.CohereConfig'>
<class 'transformers.models.blenderbot.configuration_blenderbot.BlenderbotConfig'>
<class 'transformers.models.gpt_neo.configuration_gpt_neo.GPTNeoConfig'>
<class 'transformers.models.rembert.configuration_rembert.RemBertConfig'>
<class 'transformers.models.dbrx.configuration_dbrx.DbrxConfig'>
<class 'transformers.models.xmod.configuration_xmod.XmodConfig'>
<class 'transformers.models.persimmon.configuration_persimmon.PersimmonConfig'>
<class 'transformers.models.xlm.configuration_xlm.XLMConfig'>
<class 'transformers.models.gpt_neox_japanese.configuration_gpt_neox_japanese.GPTNeoXJapaneseConfig'>
<class 'transformers.models.deprecated.mega.configuration_mega.MegaConfig'>
<class 'transformers.models.deprecated.qdqbert.configuration_qdqbert.QDQBertConfig'>
<class 'transformers.models.mbart.configuration_mbart.MBartConfig'>
<class 'transformers.models.roberta_prelayernorm.configuration_roberta_prelayernorm.RobertaPreLayerNormConfig'>
<class 'transformers.models.blenderbot_small.configuration_blenderbot_small.BlenderbotSmallConfig'>
<class 'transformers.models.ernie.configuration_ernie.ErnieConfig'>
<class 'transformers.models.mpt.configuration_mpt.MptConfig'>
<class 'transformers.models.nemotron.configuration_nemotron.NemotronConfig'>
<class 'transformers.models.bart.configuration_bart.BartConfig'>
<class 'transformers.models.gemma.configuration_gemma.GemmaConfig'>
<class 'transformers.models.opt.configuration_opt.OPTConfig'>
<class 'transformers.models.mamba.configuration_mamba.MambaConfig'>
<class 'transformers.models.musicgen.configuration_musicgen.MusicgenConfig'>
<class 'transformers.models.electra.configuration_electra.ElectraConfig'>
<class 'transformers.models.roformer.configuration_roformer.RoFormerConfig'>
<class 'transformers.models.whisper.configuration_whisper.WhisperConfig'>
<class 'transformers.models.bloom.configuration_bloom.BloomConfig'>
<class 'transformers.models.fuyu.configuration_fuyu.FuyuConfig'>
<class 'transformers.models.deprecated.xlm_prophetnet.configuration_xlm_prophetnet.XLMProphetNetConfig'>
<class 'transformers.models.openai.configuration_openai.OpenAIGPTConfig'>
<class 'transformers.models.bert_generation.configuration_bert_generation.BertGenerationConfig'>
<class 'transformers.models.biogpt.configuration_biogpt.BioGptConfig'>
<class 'transformers.models.xlnet.configuration_xlnet.XLNetConfig'>
<class 'transformers.models.jamba.configuration_jamba.JambaConfig'>
<class 'transformers.models.mixtral.configuration_mixtral.MixtralConfig'>
<class 'transformers.models.megatron_bert.configuration_megatron_bert.MegatronBertConfig'>
<class 'transformers.models.deprecated.open_llama.configuration_open_llama.OpenLlamaConfig'>
<class 'transformers.models.gptj.configuration_gptj.GPTJConfig'>
<class 'transformers.models.xglm.configuration_xglm.XGLMConfig'>
<class 'transformers.models.codegen.configuration_codegen.CodeGenConfig'>
<class 'transformers.models.gpt2.configuration_gpt2.GPT2Config'>
<class 'transformers.models.prophetnet.configuration_prophetnet.ProphetNetConfig'>
<class 'transformers.models.xlm_roberta_xl.configuration_xlm_roberta_xl.XLMRobertaXLConfig'>
<class 'transformers.models.reformer.configuration_reformer.ReformerConfig'>
<class 'transformers.models.cpmant.configuration_cpmant.CpmAntConfig'>
<class 'transformers.models.llama.configuration_llama.LlamaConfig'>
<class 'transformers.models.pegasus.configuration_pegasus.PegasusConfig'>
<class 'transformers.models.deprecated.speech_to_text_2.configuration_speech_to_text_2.Speech2Text2Config'>
<class 'transformers.models.bert.configuration_bert.BertConfig'>
<class 'transformers.models.qwen2_moe.configuration_qwen2_moe.Qwen2MoeConfig'>
<class 'transformers.models.olmo.configuration_olmo.OlmoConfig'>
<class 'transformers.models.falcon.configuration_falcon.FalconConfig'>
<class 'transformers.models.recurrent_gemma.configuration_recurrent_gemma.RecurrentGemmaConfig'>
<class 'transformers.models.mistral.configuration_mistral.MistralConfig'>
<class 'transformers.models.jetmoe.configuration_jetmoe.JetMoeConfig'>
<class 'transformers.models.phi3.configuration_phi3.Phi3Config'>
<class 'transformers.models.starcoder2.configuration_starcoder2.Starcoder2Config'>
<class 'transformers.models.plbart.configuration_plbart.PLBartConfig'>
<class 'transformers.models.git.configuration_git.GitConfig'>
<class 'transformers.models.qwen2.configuration_qwen2.Qwen2Config'>
<class 'transformers.models.gpt_bigcode.configuration_gpt_bigcode.GPTBigCodeConfig'>
<class 'transformers.models.trocr.configuration_trocr.TrOCRConfig'>
<class 'transformers.models.deprecated.transfo_xl.configuration_transfo_xl.TransfoXLConfig'>
<class 'transformers.models.rwkv.configuration_rwkv.RwkvConfig'>
<class 'transformers.models.roc_bert.configuration_roc_bert.RoCBertConfig'>
<class 'transformers.models.phi.configuration_phi.PhiConfig'>
<class 'transformers.models.roberta.configuration_roberta.RobertaConfig'>
<class 'transformers.models.bigbird_pegasus.configuration_bigbird_pegasus.BigBirdPegasusConfig'>
<class 'transformers.models.gemma2.configuration_gemma2.Gemma2Config'>
"""

"""
模型参数类的定义
"""


@dataclass
class ModelArguments:
    """
    Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
    模型的名称和路径
    """
    model_name_or_path: Optional[str] = field(
        default=None,
        metadata={
            "help": (
                "The model checkpoint for weights initialization. Don't set if you want to train a model from scratch."
            )
        },
    )
    """
    模型的类型 MODEL_TYPES 中的类型
    """
    model_type: Optional[str] = field(
        default=None,
        metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
    )
    config_overrides: Optional[str] = field(
        default=None,
        metadata={
            "help": (
                "Override some existing default config settings when a model is trained from scratch. Example: "
                "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
            )
        },
    )
    config_name: Optional[str] = field(
        default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
    )
    """
    如果预训练模型的 tokenizer 或者 path 的名称和模型名称不一致的情况下，需要重新制定 分词器的名称
    """
    tokenizer_name: Optional[str] = field(
        default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
    )
    """
    模型的存储路径
    """
    cache_dir: Optional[str] = field(
        default=None,
        metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
    )
    """
    是否使用快速分词器，一般模型默认都是True
    """
    use_fast_tokenizer: bool = field(
        default=True,
        metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
    )
    model_revision: str = field(
        default="main",
        metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
    )
    token: str = field(
        default=None,
        metadata={
            "help": (
                "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
                "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
            )
        },
    )
    """
    有些情况下，你下载的数据集或者模型自带一些处理代码，如果想让他们生效，需要设置这个值为True
    """
    trust_remote_code: bool = field(
        default=False,
        metadata={
            "help": (
                "Whether to trust the execution of code from datasets/models defined on the Hub."
                " This option should only be set to `True` for repositories you trust and in which you have read the"
                " code, as it will execute code present on the Hub on your local machine."
            )
        },
    )
    torch_dtype: Optional[str] = field(
        default=None,
        metadata={
            "help": (
                "Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the "
                "dtype will be automatically derived from the model's weights."
            ),
            "choices": ["auto", "bfloat16", "float16", "float32"],
        },
    )
    low_cpu_mem_usage: bool = field(
        default=False,
        metadata={
            "help": (
                "It is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded. "
                "set True will benefit LLM loading time and RAM consumption."
            )
        },
    )

    def __post_init__(self):
        if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
            raise ValueError(
                "--config_overrides can't be used in combination with --config_name or --model_name_or_path"
            )


@dataclass
class DataTrainingArguments:
    """
    Arguments pertaining to what data we are going to input our model for training and eval.
    """
    """
    直接传递名称，将会去官网下载
    """
    # https://www.haitianruisheng.com/dsvoice/catid-60.htm?bd_vid=11374467624987752077
    dataset_name: Optional[str] = field(
        default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
    )
    dataset_config_name: Optional[str] = field(
        default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
    )
    train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
    validation_file: Optional[str] = field(
        default=None,
        metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
    )
    max_train_samples: Optional[int] = field(
        default=None,
        metadata={
            "help": (
                "For debugging purposes or quicker training, truncate the number of training examples to this "
                "value if set."
            )
        },
    )
    max_eval_samples: Optional[int] = field(
        default=None,
        metadata={
            "help": (
                "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
                "value if set."
            )
        },
    )
    """
    支持流式处理
    """
    streaming: bool = field(default=False, metadata={"help": "Enable streaming mode"})
    block_size: Optional[int] = field(
        default=None,
        metadata={
            "help": (
                "Optional input sequence length after tokenization. "
                "The training dataset will be truncated in block of this size for training. "
                "Default to the model max input length for single sentence inputs (take into account special tokens)."
            )
        },
    )
    overwrite_cache: bool = field(
        default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
    )
    validation_split_percentage: Optional[int] = field(
        default=5,
        metadata={
            "help": "The percentage of the train set used as validation set in case there's no validation split"
        },
    )
    """
    利用多核处理训练数据
    """
    preprocessing_num_workers: Optional[int] = field(
        default=None,
        metadata={"help": "The number of processes to use for the preprocessing."},
    )
    keep_linebreaks: bool = field(
        default=True, metadata={"help": "Whether to keep line breaks when using TXT files or not."}
    )

    def __post_init__(self):
        if self.streaming:
            require_version("datasets>=2.0.0", "The streaming feature requires `datasets>=2.0.0`")

        if self.dataset_name is None and self.train_file is None and self.validation_file is None:
            raise ValueError("Need either a dataset name or a training/validation file.")
        else:
            if self.train_file is not None:
                extension = self.train_file.split(".")[-1]
                assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
            if self.validation_file is not None:
                extension = self.validation_file.split(".")[-1]
                assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."


def main():
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.
    """
    利用参数解析器对模型参数、数据参数和训练参数进行解析
    """
    parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
    if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
        print("模型参数", model_args)
        print("数据集的参数", data_args)
        print("训练参数", training_args)
    else:
        # model_args, data_args, training_args = parser.parse_args_into_dataclasses()
        model_args, data_args, training_args = parser.parse_json_file(json_file="config.json")
        print("模型参数", model_args)
        print("数据集的参数", data_args)
        print("训练参数", training_args)

    # python your_script.py config.json
    #
    # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
    # information sent is the one passed as arguments along with your Python/PyTorch versions.
    """
    在线模式状态下完成某种远程测试，这里没有意义。
    """
    # send_example_telemetry("run_clm", model_args, data_args)
    #########################################################################################################
    # Setup logging
    """
    log相关配置 
    """
    logging.basicConfig(
        format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
        datefmt="%m/%d/%Y %H:%M:%S",
        handlers=[logging.StreamHandler(sys.stdout)],
    )

    if training_args.should_log:
        # The default of training_args.log_level is passive, so we set log level at info here to have that default.
        transformers.utils.logging.set_verbosity_info()

    log_level = training_args.get_process_log_level()
    logger.setLevel(log_level)
    datasets.utils.logging.set_verbosity(log_level)
    transformers.utils.logging.set_verbosity(log_level)
    transformers.utils.logging.enable_default_handler()
    transformers.utils.logging.enable_explicit_format()

    # Log on each process the small summary:
    logger.warning(
        f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, "
        + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
    )
    logger.info(f"Training/evaluation parameters {training_args}")
    #########################################################################################################
    # Detecting last checkpoint.
    last_checkpoint = None
    if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
        # 获取最后的训练检查点
        last_checkpoint = get_last_checkpoint(training_args.output_dir)
        if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
            raise ValueError(
                f"Output directory ({training_args.output_dir}) already exists and is not empty. "
                "Use --overwrite_output_dir to overcome."
            )
        elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
            logger.info(
                f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
                "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
            )

    # Set seed before initializing model.
    # 设定一个训练的种子。
    set_seed(training_args.seed)

    # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
    # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
    # (the dataset will be downloaded automatically from the datasets Hub).
    #
    # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
    # 'text' is found. You can easily tweak this behavior (see below).
    #
    # In distributed training, the load_dataset function guarantee that only one local process can concurrently
    # download the dataset.
    """
    data_dir = '/data/datasets/alpaca_data_zh/alpaca_gpt4_data_zh.json'
    pretrain_model_dir = "/data/models/modelscope/modelscope/Llama-2-7b-ms"
    save_dir = '/data/logs/Llama-2-7b-ms_1b4_lora_tuning'
    """

    """
    1、如果明确指定了 dataset_name = 数据名称 ,该名称可以是huggingface标准地址 例如：打开 https://huggingface.co/datasets/rajpurkar/squad/viewer 的连接
    左上角一个可以复制的地方 rajpurkar/squad ，这种方法用于在线下载和存储数据集合，不适用于国内环境。一般情况下，下载会有困难，
    2、最好是将数据目录下载下来，然后直接配置 dataset_name=数据目录 数据目录也可以是已经处理好的 .parquet 文件
    3、处理之后的信息会存放到 模型指定的 cache_dir 目录下面 以特殊的形式存在，如果有记录日志，则会受到类似如下内容的反馈，记录文件具体的cache村访位置
    Using custom data configuration default-c1f89bd56af7cae5
    /media/dengyunfei/6T/data/logs/run_clm/models_cache/json/default-c1f89bd56af7cae5/0.0.0/f4e89e8750d5d5ffbef2c078bf0ddfedef29dc2faff52a6255cf513c05eb1092
    目录下一般存放两类文件 json格式的配置文件 dataset_info.json arrow类的数据文件 json-train.arrow """
    if data_args.dataset_name is not None:
        # Downloading and loading a dataset from the hub.
        raw_datasets = load_dataset(
            data_args.dataset_name,
            data_args.dataset_config_name,
            # 数据的 cache 地址使用了模型参数的 cache_dir 参数
            cache_dir=model_args.cache_dir,
            token=model_args.token,
            streaming=data_args.streaming,
            trust_remote_code=model_args.trust_remote_code,
        )
        if "validation" not in raw_datasets.keys():
            raw_datasets["validation"] = load_dataset(
                data_args.dataset_name,
                data_args.dataset_config_name,
                split=f"train[:{data_args.validation_split_percentage}%]",
                cache_dir=model_args.cache_dir,
                token=model_args.token,
                streaming=data_args.streaming,
                trust_remote_code=model_args.trust_remote_code,
            )
            raw_datasets["train"] = load_dataset(
                data_args.dataset_name,
                data_args.dataset_config_name,
                split=f"train[{data_args.validation_split_percentage}%:]",
                cache_dir=model_args.cache_dir,
                token=model_args.token,
                streaming=data_args.streaming,
                trust_remote_code=model_args.trust_remote_code,
            )
        print("raw_datasets", raw_datasets)
    else:
        data_files = {}
        dataset_args = {}
        if data_args.train_file is not None:
            data_files["train"] = data_args.train_file
        if data_args.validation_file is not None:
            data_files["validation"] = data_args.validation_file
        extension = (
            data_args.train_file.split(".")[-1]
            if data_args.train_file is not None
            else data_args.validation_file.split(".")[-1]
        )
        if extension == "txt":
            extension = "text"
            dataset_args["keep_linebreaks"] = data_args.keep_linebreaks
        raw_datasets = load_dataset(
            extension,
            data_files=data_files,
            cache_dir=model_args.cache_dir,
            token=model_args.token,
            **dataset_args,
        )
        print(dataset_args, "dataset_args")
        # If no validation data is there, validation_split_percentage will be used to divide the dataset.
        if "validation" not in raw_datasets.keys():
            raw_datasets["validation"] = load_dataset(
                extension,
                data_files=data_files,
                split=f"train[:{data_args.validation_split_percentage}%]",
                cache_dir=model_args.cache_dir,
                token=model_args.token,
                **dataset_args,
            )
            raw_datasets["train"] = load_dataset(
                extension,
                data_files=data_files,
                split=f"train[{data_args.validation_split_percentage}%:]",
                cache_dir=model_args.cache_dir,
                token=model_args.token,
                **dataset_args,
            )
        print("raw_datasets", raw_datasets)

    # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
    # https://huggingface.co/docs/datasets/loading_datasets.

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.

    config_kwargs = {
        "cache_dir": model_args.cache_dir,
        "revision": model_args.model_revision,
        "token": model_args.token,
        "trust_remote_code": model_args.trust_remote_code,
    }
    if model_args.config_name:
        config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)
    elif model_args.model_name_or_path:
        # 配置了 model_name_or_path 之后，将直接加载下面的模型
        config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs)
    else:
        config = CONFIG_MAPPING[model_args.model_type]()
        logger.warning("You are instantiating a new config instance from scratch.")
        if model_args.config_overrides is not None:
            logger.info(f"Overriding config: {model_args.config_overrides}")
            config.update_from_string(model_args.config_overrides)
            logger.info(f"New config: {config}")

    tokenizer_kwargs = {
        "cache_dir": model_args.cache_dir,
        "use_fast": model_args.use_fast_tokenizer,
        "revision": model_args.model_revision,
        "token": model_args.token,
        "trust_remote_code": model_args.trust_remote_code,
    }
    print("tokenizer_kwargs", tokenizer_kwargs)

    # 加载分词器
    if model_args.tokenizer_name:
        tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)
    elif model_args.model_name_or_path:
        tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs)
    else:
        raise ValueError(
            "You are instantiating a new tokenizer from scratch. This is not supported by this script. "
            "You can do it from another script, save it, and load it from here, using --tokenizer_name."
        )

    # 加载模型 CLM 模型当然要使用 AutoModelForCausalLM 模型加载器
    if model_args.model_name_or_path:
        torch_dtype = (
            model_args.torch_dtype
            if model_args.torch_dtype in ["auto", None]
            else getattr(torch, model_args.torch_dtype)
        )
        model = AutoModelForCausalLM.from_pretrained(
            model_args.model_name_or_path,
            from_tf=bool(".ckpt" in model_args.model_name_or_path),
            config=config,
            cache_dir=model_args.cache_dir,
            revision=model_args.model_revision,
            token=model_args.token,
            trust_remote_code=model_args.trust_remote_code,
            torch_dtype=torch_dtype,
            low_cpu_mem_usage=model_args.low_cpu_mem_usage,
        )
    else:
        model = AutoModelForCausalLM.from_config(config, trust_remote_code=model_args.trust_remote_code)
        n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values())
        logger.info(f"Training new model from scratch - Total size={n_params / 2 ** 20:.2f}M params")

    # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
    # on a small vocab and want a smaller embedding size, remove this test.
    embedding_size = model.get_input_embeddings().weight.shape[0]
    # embedding_size 一般指向模型词表大小的配置 config.vocab_size 一般两者是一致的
    # self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
    print("embedding层参数信息,以及 tokenizer 词表大小", model.get_input_embeddings().weight.shape, len(tokenizer))
    # torch.Size([42437, 1024]) 当词表的大小大于嵌入层输入大小的时候,修改嵌入层接收的输入size参数,以适配新的词表大小.此处忽略.
    if len(tokenizer) > embedding_size:
        model.resize_token_embeddings(len(tokenizer))

    # Preprocessing the datasets.
    # First we tokenize all the texts.
    if training_args.do_train:
        column_names = list(raw_datasets["train"].features)
    else:
        column_names = list(raw_datasets["validation"].features)
    text_column_name = "text" if "text" in column_names else column_names[0]

    # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function
    tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base")
    print("text_column_name", text_column_name)

    # 问答数据处理
    # def custom_process_func(example):
    #     MAX_LENGTH = 2048
    #     input_ids, attention_mask, labels = [], [], []
    #     instruction = tokenizer(
    #         "\n".join(["Human: " + example["instruction"], example["input"]]).strip() + "\n\nAssistant: ")
    #     response = tokenizer(example["output"] + tokenizer.eos_token)
    #     input_ids = instruction["input_ids"] + response["input_ids"]
    #     attention_mask = instruction["attention_mask"] + response["attention_mask"]
    #     labels = [-100] * len(instruction["input_ids"]) + response["input_ids"]
    #     if len(input_ids) > MAX_LENGTH:
    #         input_ids = input_ids[:MAX_LENGTH]
    #         attention_mask = attention_mask[:MAX_LENGTH]
    #         labels = labels[:MAX_LENGTH]
    #     return {
    #         "input_ids": input_ids,
    #         "attention_mask": attention_mask,
    #         "labels": labels
    #     }
    # lm_datasets_train = raw_datasets.map(custom_process_func,
    #                                      # batched=True,
    #                                      num_proc=data_args.preprocessing_num_workers,
    #                                      remove_columns=raw_datasets['train'].column_names,
    #                                      desc="Running custom data handler on training dataset")
    # lm_datasets_val = raw_datasets.map(custom_process_func,
    #                                    # batched=True,
    #                                    num_proc=data_args.preprocessing_num_workers,
    #                                    remove_columns=raw_datasets['validation'].column_names,
    #                                    desc="Running custom data handler on testing dataset")
    # print(lm_datasets_train)
    # print(lm_datasets_val)
    #
    # print(lm_datasets_train.keys())
    # for i in range(30,32):
    #     print("数据")
    #     print("lm_datasets",len(lm_datasets_train['train']['input_ids'][i]),lm_datasets_train['train']['input_ids'][i])
    #     print("lm_datasets",len(lm_datasets_train['train']['attention_mask'][i]),lm_datasets_train['train']['attention_mask'][i])
    #     print("lm_datasets",len(lm_datasets_train['train']['labels'][i]),lm_datasets_train['train']['labels'][i])

    def tokenize_function(examples):
        with CaptureLogger(tok_logger) as cl:
            output = tokenizer(examples[text_column_name])
        # clm input could be much much longer than block_size
        if "Token indices sequence length is longer than the" in cl.out:
            tok_logger.warning(
                "^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits"
                " before being passed to the model."
            )
        return output

    with training_args.main_process_first(desc="dataset map tokenization"):
        if not data_args.streaming:
            # map 函数的处理方式，非常优秀
            tokenized_datasets = raw_datasets.map(
                tokenize_function,
                batched=True,
                num_proc=data_args.preprocessing_num_workers,
                remove_columns=column_names,
                load_from_cache_file=not data_args.overwrite_cache,
                desc="Running tokenizer on dataset",
            )
        else:
            tokenized_datasets = raw_datasets.map(
                tokenize_function,
                batched=True,
                remove_columns=column_names,
            )

    if hasattr(config, "max_position_embeddings"):
        max_pos_embeddings = config.max_position_embeddings
    else:
        # Define a default value if the attribute is missing in the config.
        max_pos_embeddings = 1024

    if data_args.block_size is None:
        block_size = tokenizer.model_max_length
        if block_size > max_pos_embeddings:
            logger.warning(
                f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
                f"Using block_size={min(1024, max_pos_embeddings)} instead. You can change that default value by passing --block_size xxx."
            )
            if max_pos_embeddings > 0:
                block_size = min(1024, max_pos_embeddings)
            else:
                block_size = 1024
    else:
        if data_args.block_size > tokenizer.model_max_length:
            logger.warning(
                f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model "
                f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
            )
        block_size = min(data_args.block_size, tokenizer.model_max_length)
    print("block_size 大小 ,也就是最大能接受文本的长度 ", block_size)

    # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
    def group_texts(examples):
        sum = 0
        index = 0
        for  i in examples["input_ids"]:
            sum+=len(i)
            index+=1
        """
        统计 examples 1000 个 样本的总字数，整除 block_size，得到分组数，然后返回处理后的信息
        假设 :1000 个句子 总共是 10253 个字
        将这些字连在一起整除 block_size(2048) 得到的商是 5
        block_size = 2048
        total_length 10240 
        labels  和 input_ids 设置为一样
        result["labels"] = result["input_ids"].copy()
        result 的 labels 的长度就是 5
        """
        # Concatenate all texts.
        concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}

        total_length = len(concatenated_examples[list(examples.keys())[0]])
        # We drop the small remainder, and if the total_length < block_size  we exclude this batch and return an empty dict.
        # We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
        total_length = (total_length // block_size) * block_size

        # Split by chunks of max_len.
        result = {
            k: [t[i: i + block_size] for i in range(0, total_length, block_size)]
            for k, t in concatenated_examples.items()
        }
        result["labels"] = result["input_ids"].copy()
        return result

    # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
    # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
    # to preprocess.
    #
    # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
    # https://huggingface.co/docs/datasets/process#map

    with training_args.main_process_first(desc="grouping texts together"):
        if not data_args.streaming:
            lm_datasets = tokenized_datasets.map(
                group_texts,
                batched=True,
                num_proc=data_args.preprocessing_num_workers,
                load_from_cache_file=not data_args.overwrite_cache,
                desc=f"Grouping texts in chunks of {block_size}",
            )
        else:
            lm_datasets = tokenized_datasets.map(
                group_texts,
                batched=True,
            )
    print("数据处理完毕 lm_datasets", lm_datasets)
    for i in range(0, 10):
        print("数据")
        print("lm_datasets1", len(lm_datasets['train'][i]['input_ids']))
        print("lm_datasets2", len(lm_datasets['train'][i]['attention_mask']))
        print("lm_datasets3", len(lm_datasets['train'][i]['labels']))

    if training_args.do_train:
        if "train" not in tokenized_datasets:
            raise ValueError("--do_train requires a train dataset")
        train_dataset = lm_datasets["train"]
        if data_args.max_train_samples is not None:
            max_train_samples = min(len(train_dataset), data_args.max_train_samples)
            train_dataset = train_dataset.select(range(max_train_samples))
        print("是训练吗 training_args.do_train", training_args.do_train)

    if training_args.do_eval:
        print("是验证吗 training_args.do_eval", training_args.do_eval)
        if "validation" not in tokenized_datasets:
            raise ValueError("--do_eval requires a validation dataset")
        eval_dataset = lm_datasets["validation"]
        print("if data_args.max_eval_samples is not None")
        if data_args.max_eval_samples is not None:
            max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
            eval_dataset = eval_dataset.select(range(max_eval_samples))

        def preprocess_logits_for_metrics(logits, labels):
            if isinstance(logits, tuple):
                # Depending on the model and config, logits may contain extra tensors,
                # like past_key_values, but logits always come first
                logits = logits[0]
            return logits.argmax(dim=-1)

        print("evaluate.load")
        # 这里不修改容易卡住

        metric = evaluate.load('/media/dengyunfei/6T/evaluate-main/metrics/accuracy')
        # 官方给出的方法会卡死
        # metric = evaluate.load("accuracy", cache_dir=model_args.cache_dir)
        print("def compute_metrics(eval_preds)")

        def compute_metrics(eval_preds):
            preds, labels = eval_preds
            # preds have the same shape as the labels, after the argmax(-1) has been calculated
            # by preprocess_logits_for_metrics but we need to shift the labels
            labels = labels[:, 1:].reshape(-1)
            preds = preds[:, :-1].reshape(-1)
            return metric.compute(predictions=preds, references=labels)

    # Initialize our Trainer
    print("初始化训练器", is_torch_xla_available())

    """
    processing_class 可填写参数必须是如下类型：PreTrainedTokenizerBase 或 BaseImageProcessor 或 FeatureExtractionMixin 或 ProcessorMixin
        print("tokenizer",tokenizer.__class__)
        from transformers.models.bloom.tokenization_bloom_fast import BloomTokenizerFast
    
    data_collator 该函数用于从 train_dataset 或 eval_dataset 的元素列表中形成一个批次。
    如果没有提供 processing_class ，则默认使用[default_data_collator]；
    
    如果 processing_class 是一个特征提取器或分词器，则默认使用[DataCollatorWithPadding]的实例。
    本例子中 processing_class 是一个分词器，但是不能用默认的 DataCollatorWithPadding。
    因此指定  data_collator=default_data_collator 
    
    对比 DataCollatorWithPadding 和 DefaultDataCollator：
    DefaultDataCollator 是一个超简单的类，其 __call__ 方法调用了 default_data_collator 函数进行处理，并指定了 tensor 的输出格式。 
    DataCollatorWithPadding 也是一个处理函数类，使用快速分词法，将数据进行分词并填充、同时完成对label和labels_ids标签的标准化，都转换为labels。
    
    preprocess_logits_for_metrics 为logits和labels做一系列的处理以便进行 metrics 测算的方法。这里只是将 logits 进行 softmax 处理，没有调整labels。
    """
    print("compute_metrics if training_args.do_eval and not is_torch_xla_available() else None",
          compute_metrics if training_args.do_eval and not is_torch_xla_available() else None)

    def compute_metrics(eval_preds):
        preds, labels = eval_preds
        # preds have the same shape as the labels, after the argmax(-1) has been calculated
        # by preprocess_logits_for_metrics but we need to shift the labels
        # print("验证过程中，没有正确和失败之分。因此这里无法使用准确率来进行评判。")
        # print(preds.shape, labels.shape)
        # # (20, 2048) (20, 2048)
        # [INFO|trainer.py:4119] 2024-11-03 14:04:47,602 >>   Num examples = 20
        # [INFO|trainer.py:4122] 2024-11-03 14:04:47,602 >>   Batch size = 2
        #
        # 由于传入的 input和labels 被处理为一样的值。
        # input  START 我是什么人，我是好人。END
        # labels START 我是什么人，我是好人。END

        # 计算的输出是从第一个字符后面出来的输出。
        # 原始的 preds = 我是什么人，我是好人。END UNK
        # preds = preds[:-1] ... = 我是什么人，我是好人。END

        # 因此这里需要取得第一个字符后面的作为输出和 preds 进行比对。
        # 原始的 labels = START 我是什么人，我是好人。END
        # labels = labels[1:] = 我是什么人，我是好人。END
        # 如果出现其他情况，需要确定好最终输出结果的一致判定。

        labels = labels[:, 1:].reshape(-1)
        preds = preds[:, :-1].reshape(-1)
        return metric.compute(predictions=preds, references=labels)

    trainer = Trainer(
        model=model,
        args=training_args,
        # 是否训练和验证，可以设置在配置中
        train_dataset=train_dataset if training_args.do_train else None,
        eval_dataset=eval_dataset if training_args.do_eval else None,
        processing_class=tokenizer,
        # Data collator will default to DataCollatorWithPadding, so we change it.
        data_collator=default_data_collator,
        compute_metrics=compute_metrics if training_args.do_eval and not is_torch_xla_available() else None,
        preprocess_logits_for_metrics=preprocess_logits_for_metrics
        if training_args.do_eval and not is_torch_xla_available()
        else None,
    )

    # Training
    if training_args.do_train:
        print("开始训练")
        checkpoint = None
        if training_args.resume_from_checkpoint is not None:
            checkpoint = training_args.resume_from_checkpoint
        elif last_checkpoint is not None:
            checkpoint = last_checkpoint
        train_result = trainer.train(resume_from_checkpoint=checkpoint)
        trainer.save_model()  # Saves the tokenizer too for easy upload

        metrics = train_result.metrics

        max_train_samples = (
            data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
        )
        metrics["train_samples"] = min(max_train_samples, len(train_dataset))

        trainer.log_metrics("train", metrics)
        trainer.save_metrics("train", metrics)
        trainer.save_state()

    # Evaluation
    if training_args.do_eval:
        print("开始评估")
        logger.info("*** Evaluate ***")

        metrics = trainer.evaluate()

        max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
        metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
        try:
            perplexity = math.exp(metrics["eval_loss"])
        except OverflowError:
            perplexity = float("inf")
        metrics["perplexity"] = perplexity

        trainer.log_metrics("eval", metrics)
        trainer.save_metrics("eval", metrics)

    kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"}
    if data_args.dataset_name is not None:
        kwargs["dataset_tags"] = data_args.dataset_name
        if data_args.dataset_config_name is not None:
            kwargs["dataset_args"] = data_args.dataset_config_name
            kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
        else:
            kwargs["dataset"] = data_args.dataset_name

    if training_args.push_to_hub:
        trainer.push_to_hub(**kwargs)
    else:
        trainer.create_model_card(**kwargs)


# def _mp_fn(index):
#     # For xla_spawn (TPUs)
#     main()


if __name__ == "__main__":
    main()
